import axios, { AxiosRequestConfig } from "axios";
import { axiosStatusEnum } from "./enum";
// import { useUserStoreHook } from "@/stores/modules/userStore";

// 定义通用响应结构
export interface ApiResponse<T> {
  code: axiosStatusEnum;
  data: T;
  /** 消息 */
  message: string;
  /** 是否成功 */
  success: boolean;
}

/** 创建axios */
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 80000,
});

// showToast({ message: `API请求地址---${import.meta.env.VITE_API_URL}` });

// 添加请求拦截器
service.interceptors.request.use(
  (config: any) => {
    // console.log("--查看请求", config);
    let token: string = '' //此处换成自己获取回来的token，通常存在在cookie或者store里面
    // let token: string = useUserStoreHook().userInfo.Token; //此处换成自己获取回来的token，通常存在在cookie或者store里面
    if (token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers["X-Token"] = token;
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log("出错啦", error); // for debug
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: any) => {
    const data = response.data;
    // const { data } = response;
    const code = data.code;

    if (code !== axiosStatusEnum.normal) {
      if (
        code === axiosStatusEnum.not_certified ||
        code === axiosStatusEnum.no_permissions
      ) {
        // showToast({ message: data.message || "权限错误", duration: 5000 });
        return Promise.reject(new Error(data.message || "权限错误"));
      } else if (code === axiosStatusEnum.server_error) {
        // showToast({ message: data.message || "服务器错误", duration: 5000 });
        return Promise.reject(new Error(data.message || "服务器错误"));
      }
    }

    return data;
  },
  (error) => {
    console.log("err" + error); // for debug
    // showToast({
    //   message: error || "服务器错误",
    //   duration: 5000,
    // });
    return Promise.reject(error);
  }
);

export function serviceGet<T = any>(
  config: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return service({ ...config, method: "GET" });
}

export function servicePost<T = any>(
  config: AxiosRequestConfig
): Promise<ApiResponse<T>> {
  return service({ ...config, method: "POST" });
}

export default service;
